<template>
	<view class="updata">
		<toSafe :bgColor="'#fff'"></toSafe>
		<view class="search-top">
			<uni-icons type="left" size="30" @click="HandleReturn" style="margin-right: 20rpx;"></uni-icons>
			<view>上 传 照 片</view>
		</view>
		<view style="font-size: 24rpx;color: #ca0000;">
			注：请上传大小在1024kb以内的jpg或png图片!
		</view>
		<scroll-view :scroll-y="true" class="updata-body">
			<view class="update-receipt">
				<view class="receipt-title">
					上传凭条
				</view>
				<!-- <uni-file-picker v-model="entrySlip" file-mediatype="image" file-extname="png,jpg" :limit="9"
					@success="success" @fail="failHandler"></uni-file-picker> -->
				<view class="" v-if="!isRoles">
					<up-upload :fileList="entrySlip" :disabled="true" v-if="entrySlip.length == 0"></up-upload>
					<up-upload :fileList="entrySlip" :previewFullImage="true" v-else @afterRead="entryAfterRead"
						@delete="entryDeletePic" name="1" multiple :maxCount="99"
						:deletable="isRoles"></up-upload>
				</view>
				<view class="" v-else>
					<up-upload :fileList="entrySlip" :previewFullImage="true" @afterRead="entryAfterRead"
						@delete="entryDeletePic" name="1" multiple :maxCount="99"></up-upload>
				</view>
			</view>
			<view class="updata-photo">
				<view class="receipt-title">
					上传现场照片
				</view>
				<!-- <uni-file-picker v-model="sitePhoto" file-mediatype="image" file-extname="png,jpg" :limit="9"
					@fail="failHandler"></uni-file-picker> -->
				<view class="" v-if="!isRoles">
					<up-upload :fileList="sitePhoto" :disabled="true" v-if="sitePhoto.length == 0"></up-upload>
					<up-upload :fileList="sitePhoto" :previewFullImage="true" v-else @afterRead="siteAfterRead"
						@delete="siteDeletePic" name="2" multiple :maxCount="99"
						:deletable="isRoles"></up-upload>
				</view>
				<view class="" v-else>
					<up-upload :fileList="sitePhoto" :previewFullImage="true" @afterRead="siteAfterRead"
						@delete="siteDeletePic" name="2" multiple :maxCount="99"></up-upload>
				</view>
			</view>
		</scroll-view>
		<button class="next" @click="submit" v-if="isRoles">提交</button>
	</view>
</template>

<script setup>
	import Config from '@/config.js'
	import toSafe from '@/compoents/top-safe.vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		submitReceipt,
		getReceipt
	} from '@/api/maintenance.js'
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	let form = ref({
		id: '',
		entrySlip: '',
		sitePhoto: '',
	})
	import {
		getToken
	} from '@/utils/auth'
	let entrySlip = reactive([])
	let sitePhoto = reactive([])
	let isRoles = ref(true)
	const testStatus = ref('')
	onMounted(() => {})
	onLoad(options => {
		form.value.id = options.id
		isRoles.value = JSON.parse(options.isRoles)
		testStatus.value = options.status
		getReceiptList()
		// getRoles()
	})
	const HandleReturn = () => {
		uni.navigateBack({
			delta: 1
		});
	}
	const getRoles = () => {
		let roles = uni.getStorageSync('roles')
		roles.split(',').forEach(item => {
			if (item == '一级消防师' || item == '工程师') {
				isRoles.value = false
			} else {
				isRoles.value = true
			}
		})
	}
	const getReceiptList = async () => {
		let res = await getReceipt({
			planId: form.value.id
		})
		if (res.code == 200) {
			if (res.data.entrySlip) {
				const isEntrySlip = res.data.entrySlip?.split(',')
				if (isEntrySlip.length) {
					isEntrySlip.forEach(item => {
						entrySlip.push({
							status: 'success',
							message: '',
							url: Config.baseUrl + item,
						});
					})
				} else {
					entrySlip = []
				}
			}
			if (res.data.sitePhoto) {
				const isSitePhoto = res.data.sitePhoto?.split(',')
				if (isSitePhoto.length) {
					isSitePhoto.forEach(item => {
						sitePhoto.push({
							status: 'success',
							message: '',
							url: Config.baseUrl + item,
						});
					})
				} else {
					sitePhoto = []
				}
			}
		}
	}
	const getImageValue = (url) => {
		if (url) {
			if (url.indexOf('prod-api') != -1) {
				console.log(url.split('prod-api'));
				return url.split('prod-api')[1]
			} else {
				return url
			}
		} else {
			return null
		}
	}
	const submit = () => {
		let entrySlipList = []
		let sitePhotoList = []
		// console.log(entrySlip, sitePhoto);
		entrySlip.forEach(item => {
			entrySlipList.push(getImageValue(item.url))
		})
		sitePhoto.forEach(item => {
			sitePhotoList.push(getImageValue(item.url))
		})
		form.value.entrySlip = entrySlipList.join(',')
		form.value.sitePhoto = sitePhotoList.join(',')
		console.log(testStatus.value, 'testStatus.value');
		form.value.execStatus = testStatus.value == '1' ? '2' : testStatus.value == '2' ? '3' : '5'
		console.log(form.value);
		submitReceipt(form.value).then(res => {
			if (res.code == 200) {
				uni.showToast({
					title: '凭证上传成功！'
				})
				// uni.navigateTo({
				// 	url: "/pages/maintenance/tasks"
				// })
				uni.switchTab({
					url: "/pages/index/index"
				})
			}
		})
	}
	const failHandler = () => {
		uni.showToast({
			title: '文件上传失败！'
		})
	}
	const entryAfterRead = async (event) => {
		const maxSize = 1 * 1024 * 1024; // 1MB
		const validFormats = ['png', 'jpg'];
		const files = event.file[0]
		if (files.size > maxSize) {
			uni.showToast({
				title: '文件太大，请选择小于1024kb的文件！',
				icon: 'none',
				duration: 4000
			})
			return
		}
		const urlformat = files.url.substring(files.url.length - 3)
		// console.log(files.url, urlformat, 'console.log(event);');
		// if (!validFormats.includes(urlformat)) {
		// 	uni.showToast({
		// 		title: '文件格式不正确，请上传JPG或PNG格式的图片！',
		// 		icon: 'none',
		// 		duration: 4000
		// 	})
		// 	return
		// }
		let lists = [].concat(event.file);
		let fileListLen = entrySlip.length;
		lists.map((item) => {
			entrySlip.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const res = await uploadFilePromise(lists[i].url);
			if (res.code == 200) {
				let item = entrySlip[fileListLen];
				entrySlip.splice(fileListLen, 1, {
					...item,
					status: 'success',
					message: '',
					url: res.fileName,
				});
				fileListLen++;
			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				let index = entrySlip.findIndex(item => item.message == '上传中')
				if (index != -1) {
					entrySlip.splice(index, 1)
				}
			}
		}
	}
	const siteAfterRead = async (event) => {
		const maxSize = 1 * 1024 * 1024; // 1MB
		const validFormats = ['png', 'jpg'];
		const files = event.file[0]
		if (files.size > maxSize) {
			uni.showToast({
				title: '文件太大，请选择小于1024kb的文件！',
				icon: 'none',
				duration: 4000
			})
			return
		}
		const urlformat = files.url.substring(files.url.length - 3)
		// console.log(files.url, urlformat, 'console.log(event);');
		if (!validFormats.includes(urlformat)) {
			uni.showToast({
				title: '文件格式不正确，请上传JPG或PNG格式的图片！',
				icon: 'none',
				duration: 4000
			})
			return
		}
		let lists = [].concat(event.file);
		let fileListLen = sitePhoto.length;
		lists.map((item) => {
			sitePhoto.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const res = await uploadFilePromise(lists[i].url);
			if (res.code == 200) {
				let item = sitePhoto[fileListLen];
				sitePhoto.splice(fileListLen, 1, {
					...item,
					status: 'success',
					message: '',
					url: res.fileName,
				});
				fileListLen++;
			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none'
				})
				let index = sitePhoto.findIndex(item => item.message == '上传中')
				if (index != -1) {
					sitePhoto.splice(index, 1)
				}
			}
		}
	}
	const uploadFilePromise = (url) => {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: 'https://xf.xiaoyiyunwang.com/prod-api/common/upload',
				filePath: url,
				name: 'file',
				formData: {
					user: 'test',
				},
				header: {
					'Authorization': 'Bearer ' + getToken()
				},
				success: (res) => {
					resolve(JSON.parse(res.data));
				},
			});
		});
	};
	// 上传成功
	function success(e) {
		console.log('上传成功')
	}
	// 删除图片
	const entryDeletePic = (event) => {
		entrySlip.splice(event.index, 1);
	};
	// 删除图片
	const siteDeletePic = (event) => {
		sitePhoto.splice(event.index, 1);
	};
</script>

<style lang="less" scoped>
	@import "../../App.less";

	.updata {
		width: 100%;
		height: 100%;
		background: #fff;
		padding: 0 28rpx;
		overflow: hidden;

		.search-top {
			height: 88rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.left {
				width: 48rpx;
			}

			view {
				flex: 1;
				line-height: 88rpx;
				height: 88rpx;
				padding-right: 48rpx;
				text-align: center;
				font-size: 34rpx;
				font-weight: 700;
			}
		}

		.info-search {

			.search_icons {
				margin: 20rpx 0;
				.inline_center();
				width: 100%;
				height: 68rpx;
				padding: 16rpx 20rpx;
				background-color: #F2F2F2;
				border-radius: 34rpx;

				.icon {
					margin-right: 10rpx;
				}

				.uni-input {
					width: 100%;
					border-right: 1px solid #325EF5;
					margin-right: 20rpx;
					height: 100%;
				}

				.search {
					background-color: inherit;
					width: 100rpx;
					height: 68rpx;
					font-size: 32rpx;
					color: #325EF5;
					line-height: 68rpx;
				}
			}
		}

		.updata-body {
			height: calc(100vh - 88rpx);
			width: 100%;
			padding: 20rpx 0;

			.update-receipt {
				.receipt-title {
					font-size: 28rpx;
					margin-bottom: 20rpx;
				}
			}

			.updata-photo {
				margin-top: 60rpx;

				.receipt-title {
					font-size: 28rpx;
					margin-bottom: 20rpx;
				}

				&::after {
					content: '';
					display: block;
					width: 100%;
					height: 88rpx;
				}
			}
		}

		.next {
			position: absolute;
			bottom: 12rpx;
			width: calc(100vw - 56rpx);
			background-color: #325EF5;
			color: #fff;
			border-radius: 16rpx;
			z-index: 99;
		}
	}

	::v-deep .icon-add {
		background-color: #c5c6c8;
	}

	::v-deep .is-add {
		background-color: #F6F8FA;
	}
</style>